<template>
  <div id="login">
    <el-card class="box-card box-card-login">
      <div slot="header" class="clearfix">
        <span class="title">登录</span>
        <el-button style="float: right; padding: 3px 0" type="text"><router-link to="/register">注册</router-link></el-button>
      </div>
      <el-form :model="ruleForm" :rules="rules" label-width="80px" ref="ruleForm" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="请输入用户名" v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入密码" type="password" v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择角色">
            <el-option label="客户" value="1"></el-option>
            <el-option label="快递员" value="2"></el-option>
            <el-option label="网点" value="3"></el-option>
            <el-option label="中转站" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="resource">
          <el-radio-group>
            <el-checkbox label="记住密码" @change="handelChecked"></el-checkbox>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import qs from 'qs'
import router from './../../router'
import store from '@/store/index.js'
import global from '@/lib/global'
export default {
  name: 'Login',
  data () {
    return {
      resource: false, // 记住密码
      ruleForm: {
        username: '',
        password: '',
        type: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  created(){
    this.getCookie()
  },
  methods: {
    setCookie(c_name, c_pwd,c_type, exdays) {
      console.log("存入cookie:",c_name, c_pwd,c_type);
      var exdate = new Date();
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      document.cookie = "userName=" + c_name + ";path=/;expires=" + exdate.toLocaleString()
      document.cookie = "userPwd=" + c_pwd + ";path=/;expires=" + exdate.toLocaleString()
      document.cookie = "userType=" + c_type + ";path=/;expires=" + exdate.toLocaleString()
    },
      //获取cookie
    getCookie: function() {
      // console.log(document.cookie)
      if (document.cookie.length > 0) {
        var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
        // console.log(arr)
        for (var i = 0; i < arr.length; i++) {
            var arr2 = arr[i].split('='); //再次切割
            //判断查找相对应的值
            if (arr2[0] == 'userName') {
                this.ruleForm.username = arr2[1]; //保存到保存数据的地方
            } else if (arr2[0] == 'userPwd') {
                this.ruleForm.password = arr2[1];
            }else if (arr2[0] == 'userType') {
                this.ruleForm.type = arr2[1];
            }
          }
      }
    },
    //删除cookie
    clearCookie: function() {
      this.setCookie("", "","", -1); //修改2值都为空，天数为负1天就好了
    },
    handelChecked(e,checked){
      this.resource = e
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm.resource)
          if(this.resource){
            console.log("checked == true");
            //传入账号名，密码，和保存天数3个参数
            this.setCookie(this.ruleForm.username,this.ruleForm.password, this.ruleForm.type, 7);
          }else {
            console.log("清空Cookie");
            //清空Cookie
            this.clearCookie();
          }
           var ruleForm = this.ruleForm
          // alert('submit!')
          this.$axios({
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            },
            method: 'post',
            url: global.baseUrl+'/login',
            data: qs.stringify(this.ruleForm)
          })
          .then(function (resp) {
            if(resp.data.success){
              // 把token存上
              store.commit('set_token', resp.data.data);
              if(store.state.token){ 
                if(ruleForm.type == 1){
                    router.push("/express")
                    sessionStorage.userType = "客户"  
                }
                if(ruleForm.type == 2){
                    router.push("/courier")
                    sessionStorage.userType = "快递员"  
                }
                if(ruleForm.type == 3){
                    router.push("/dot")
                    sessionStorage.userType = "网点"  
                }
                if(ruleForm.type == 4){
                    router.push("/transferStation")
                    sessionStorage.userType = "中转站"  
                }
              }else{
                router.push("/login")
              }
            }else{
              alert(resp.data.message);
            }
          })
          .catch(function (error) {
            console.log(error)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style>
#login{
  width: 100%;
  height: 100%;
  background: url(./../../assets/images/login-bg.jpg) no-repeat;
  background-size: 100% 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.box-card-login{
  width: 500px;
  padding: 20px;
}
.clearfix .title{
  font-size: 22px;
}
.el-select{
  display: block;
}
.el-form-item__content{
  text-align: left;
}
</style>
